/**
 * Created by yk on 15/7/1.
 */
require(['jquery', 'jquerymobile', 'net', 'dialogs','newsroom','videoDetailed'], function($, m, net, dia,newsroom, videodetail) {
    function cleanUpListItems() {
        $("#newsroom_listview_news").empty(); 
    }
    function initPageLoad(wrapper) {
        var $wrapper = $("#" + wrapper),
            $pullDownEl = $wrapper.find("#pullDown"),
            $pullDownLabel = $pullDownEl.find(".pullDownLabel"); 
        if ($wrapper.find("ul").html()) {
            $wrapper.find(".scroller").css(window.getVendorStyle("transform"), "translate(0, 0)");
            $pullDownEl.attr("class", "loading");
            $pullDownLabel.text("Loading...");
        }
    }
    function  resetVoting(){
        $('#voting_content .sel').removeClass('sel');
        $('#voting_content .selRadio').removeClass('selRadio');
        $('#voting_content .warningText').hide();
        $('#voting_intro').css('display', 'block');
        $('#voting_individuals').css('display', 'none');
        $('#voting_team').css('display', 'none');
        $('#voting_end').css('display', 'none');
    }

    var panel_QrcodeScan = function(menuId){
        cordova.exec(function(){cordova.logger.debug("success");}, function(){cordova.logger.debug("error");}, "ShowVideoPlaybackView", "showVideoPlaybackView", []);
        cordova.exec(function(content){
            net.post('activity/getActivity', {
                'content': content,
                userId:q['user'].userId
            }, function(error){
                $(".loadingDiv").addClass("dismiss").removeClass("qrcodepage");
                dia.alert('Oops', response.msg, ['OK'], function(title) {
                    var  menuId_c = $('.ui-page-active').attr('id');
                    return panel_QrcodeScan(menuId_c);
                });
            }, function(response){
                if (response.code != 0) {
                    $(".loadingDiv").addClass("dismiss").removeClass("qrcodepage");
                    dia.alert('Oops', response.msg, ['OK'], function(title) {
                        var  menuId_c = $('.ui-page-active').attr('id');
                        return panel_QrcodeScan(menuId_c);
                    });
                }
                else{
                    var activityInfo = response.data.activity;
                    activityInfo.menuId = menuId;
                    $('#video_detailed_listview').empty();
                    $('#video_listview_comments').empty();
                    videodetail.from('#QrcodeScan');
                    activityInfo.pageId = "activities";
                    videodetail.showDetailWithNew(activityInfo);
                    videodetail.showCommentsContent();
                    $.mobile.newChangePage("#video_detailed",{ transition: "none",reverse: false,changeHash: false});
                }
            },{async:false});
        }, function(){$(".loadingDiv").addClass("dismiss").removeClass("qrcodepage");}, "ShowVideoPlaybackView", "showVideoPlaybackViewAndReceiveScan", []);
        $(".loadingDiv").addClass("qrcodepage");
    };
    // 点击菜单按钮出现菜单
    $('.panle_btn_menu').on('click', function(evt) {
        $("#inputval").blur();
        $("#inputval_ol").blur();
        setTimeout(function(){
            $('#panel_menu_extend').show();
            $('.ui-panel-inner').css({'padding':'0px'});
            $('.panel_nees_opacity').css('min-height',$(window).height());
            $('#news_content').css('max-height',$(window).height()-44);
            $('#panel_menu_extend').css('min-height',$(window).height());
            $('#panel_ul').css('max-height',$(window).height()-52-82);
            if($(window).height()-52-82 > ($("#panel_ul").attr("panle_menu_size"))*52){
                $('#panel_auto_height').css('min-height',$(window).height()-52-82-($("#panel_ul").attr("panle_menu_size"))*52);
                $('#panel_auto_height').show();
            }
            else{
                $('#panel_auto_height').hide();
            }
            var username = localStorage['username'] + '!';
            $("#panel_username").html(username);
            $(".loadingDiv").addClass("dismiss");
            $( "#panel_menu_extend" ).panel( "open" );
            $( "#panel_menu_extend" ).removeClass();
            $(".ui-panel-dismiss").remove();

            $(".loadingDiv.dismiss").on( "tap", function( event, ui ) {
                panelclose();

            });
        },300)

    });
    // 点击新闻项，菜单隐藏
    $('#panel_ul').off('click', '#panel_newsroom').on('click' , '#panel_newsroom' , function(evt) {
        var menuId = $('.ui-page-active').attr('id');
         if(menuId == "newsroom" && $("#newsroom").hasClass("newsroom")){
            panelclose();
        }
        else {
            if(menuId == "voting"){
                resetVoting();
            }
            $("#newsroom").removeClass("activities newsroom talentShow video").addClass("newsroom");
            getNewsroomData(menuId,'newsroom');
        }
    }); 
    //推出activities 页面 
    $('#panel_ul').off('click', '#panel_activities').on('click' , '#panel_activities' , function(evt) {
        var menuId = $('.ui-page-active').attr('id');
        if(menuId == "newsroom" && $("#newsroom").hasClass("activities")){
            panelclose();
        }
        else{
            if(menuId == "voting"){
                resetVoting();
            }  
            $("#newsroom").removeClass("activities newsroom talentShow video").addClass("activities");
            getNewsroomData(menuId,'activities');
        }
    });
    //点击HSBC NOW，菜单隐藏
    $('#panel_ul').off('click', '#panel_hsbcnow').on('click' , '#panel_hsbcnow' , function(evt) {
        var menuId = $('.ui-page-active').attr('id');
        if(menuId == "newsroom" && $("#newsroom").hasClass("video")){
            panelclose();
        }
        else{
            if(menuId == "voting"){
                resetVoting();
            } 
            $("#newsroom").removeClass("activities newsroom talentShow video").addClass("video");
            getNewsroomData(menuId,'video');
        }
    }); 
    // 点击Talent Show，菜单隐藏
    $('#panel_ul').off('click', '#panel_talentShow').on('click' , '#panel_talentShow' , function(evt) {
        var menuId = $('.ui-page-active').attr('id');
        if(menuId == "newsroom" && $("#newsroom").hasClass("talentShow")){
            panelclose();
        }
        else {
            if(menuId == "voting"){
                resetVoting();
            } 
            $("#newsroom").removeClass("activities newsroom talentShow video").addClass("talentShow");
            getNewsroomData(menuId,'talentShow'); 
        }
    });
    //点击Discovery菜单项
    $('#newsroom_btn_menu').off('click', '#panel_discovery').on('click' , '#panel_discovery' , function(evt) {
        var menuId = $('.ui-page-active').attr('id');
        if(menuId == "voting"){
            resetVoting();
        }
        panel_QrcodeScan(menuId);
    });
    $('#panel_ul').off('click', '#panel_GSR').on('click' , '#panel_GSR' , function(evt) {
        var menuId = $('.ui-page-active').attr('id');
        if(menuId == "voting"){
            resetVoting();
        }
        cordova.exec(function(){cordova.logger.debug("success");}, function(){cordova.logger.debug("error");}, "BYODPlugIn", "showGSR", []);
    });

    $('#panel_ul').off('click', '#panel_Laisee').on('click' , '#panel_Laisee' , function(evt) {
        var menuId = $('.ui-page-active').attr('id');
        if(menuId == "voting"){
            resetVoting();
        }
        //Green Laisee entrance
        var cuser = null;
        if (localStorage.getItem('login_user')!=null) {
            cuser = JSON.parse(localStorage.getItem('login_user'));
        } else {
            console.assert(false, '还没登录，没有用户信息可填写');
        }
        cordova.exec(function(){console.error("success")}, function(){console.error("error")}, "OpenGreenLaisee", "openGreenLaisee", [JSON.stringify({"account": ""+cuser.staffId+"", "fullName": ""+cuser.english_name+"", "secureToken": "", "location": ""+cuser.branch+"", "company": "HSBC"})]);
    });

    // 点击注销，返回登录
    $('#panel_menu_extend').off('click', '#panel_logOff').on('click' , '#panel_logOff' , function(evt) {
        var menuId = $('.ui-page-active').attr('id');
        if(menuId == "voting"){
            resetVoting();
        }
        $.mobile.newChangePage('#logon',{transition: "slide",reverse: true,changeHash: false});
        chrome.storage.internal.remove('password', function(){});
        //注销用户后复选框清空
        if(menuId == "filter"){
            $('#all_check').removeClass('nor').addClass('sel');
            $('div[name="sbox"]', $('#filter')).each(function(index, val) {
                $(val).removeClass('nor').addClass('sel');
            });  
        }
        else if(menuId == "voting"){
            $('#all_check').removeClass('sel').addClass('nor');
            $('div[name="sbox"]').each(function(index, val) {
                $(val).removeClass('sel').addClass('nor');
            });
        }
        else{
            $('.checklabel').removeClass('sel').addClass('nor');
            $('div[name="sbox"]').each(function(index, val) {
                $(val).removeClass('sel').addClass('nor');
            });
        }
        // Nick added for pull to refresh start
        cleanUpListItems();
        $(".wrapper").find("#pullUp").hide();
        
        window.shouldPageRefresh.newsroom = true; 

        if($("ul#panel_ul li.panle_pushmenu").size()){
            $("ul#panel_ul li.panle_pushmenu").remove();
        }
        q['user'] = null;
        // Nick added for pull to refresh end
    });
    //推出setting页面
    $('#panel_ul').off('click', '#panel_settings').on('click' , '#panel_settings' , function(evt) {
        var menuId = $('.ui-page-active').attr('id');
        if(menuId == "setting"){
            panelclose();
        }
        else{
            if(menuId == "voting"){
                resetVoting();
            }
            cleanUpListItems();
            $.mobile.newChangePage("#setting",{ transition: "slide",reverse: false,changeHash: false});
        }
    });
    //推出Myorner页面
    $('#panel_ul').off('click', '#panel_mycorner').on('click' , '#panel_mycorner', function(evt) {
        var menuId = $('.ui-page-active').attr('id');
        if(menuId == "mycorner"){
            panelclose();
        }
        else{
            cleanUpListItems();
            $.mobile.newChangePage("#mycorner",{ transition: "slide",reverse: false,changeHash: false});
        }
    });
    //推出book页面
    $('#panel_ul').off('click', '#panel_book').on('click' , '#panel_book', function(evt) {
        var menuId = $('.ui-page-active').attr('id');
        var title_html = $("#title_book").html();
        if(menuId == "book"){
            if(title_html == "My favorites"){
                $("#title_book").html("Book²");
                cleanUpListItems();
                window.shouldPageRefresh.book = true;
                $.mobile.newChangePage("#book",{ transition: "slide",reverse: false,changeHash: false,allowSamePageTransition:true});
            }
            panelclose();
        }
        else{
            if(title_html == "My favorites"){
                $("#title_book").html("Book²");
            }
            //panelclose();
            cleanUpListItems();
            window.shouldPageRefresh.book = true;
            $.mobile.newChangePage("#book",{ transition: "slide",reverse: false,changeHash: false,allowSamePageTransition:true});
        }
    });
    $('#panel_ul').off('click', '#panel_voting').on('click' , '#panel_voting', function(evt) {
        var menuId = $('.ui-page-active').attr('id');
        if(menuId == "voting"){ 
            panelclose();
        }
        else{
            if(menuId == "voting"){
                resetVoting();
            }
            cleanUpListItems();
            $.mobile.newChangePage("#voting",{ transition: "slide",reverse: false,changeHash: false});
        }
    }); 
    //点击CA菜单，进入CA主页面
    $('#panel_ul').off('click', '#panel_ca').on('click' , '#panel_ca', function(evt) {
        var menuId = $('.ui-page-active').attr('id');
        if(menuId == "ca"){
            panelclose();
        }
        else{
            cleanUpListItems();
            $.mobile.newChangePage("#ca",{ transition: "slide",reverse: false,changeHash: false});
            var postData = {};
            postData['userId'] = q['user'].userId;
            net.post('ca/hasCaRegData',postData,function(error){

            },function(response){
                if (response.code != 0) {
                }
                else{
                    var dataInfo = response.data.Info;
                    if(dataInfo == true){
                        $("#team_records").css("display","block");
                    }else{
                        $("#team_records").css("display","none");
                    }

                }
            });
        }
    });

    function getNewsroomData(menuId,pageId){ 
        $("#newsroom").attr("pageId",pageId);
        cleanUpListItems(); 
        initPageLoad("news_wrapper"); 
        window.shouldPageRefresh.newsroom = true;
        if(menuId != "newsroom"){
            $.mobile.newChangePage("#newsroom", { transition: "slide", reverse: false, changeHash: false});
        }
        else{
            //newsroom.templateNews();
            panelclose();
        }
        newsroom.templateNews();
    }

    function panelclose(){
         $( "#panel_menu_extend" ).addClass("ui-panel ui-panel-position-left ui-panel-display-overlay ui-body-inherit ui-panel-animate ui-panel-open");
         setTimeout(function(){
             $( "#panel_menu_extend" ).panel( "close" );
         },500);
    }
    $("#corner_content,#setting_content,#voting_content,#filter_content,#activities_content,#activity_filter_content,#video_content,#talentShow_content,#book_content,#book_check_content,#ca_content,#registration_confirm_content").on("swiperight",function(){
        $('#panel_menu_extend').show();
        $('.ui-panel-inner').css({'padding':'0px'});
        $('.panel_nees_opacity').css('min-height',$(window).height());
        $('#news_content').css('max-height',$(window).height()-44);
        $('#panel_menu_extend').css('min-height',$(window).height());
        $('#panel_ul').css('max-height',$(window).height()-52-82);
        if($(window).height()-52-82 > ($("#panel_ul").attr("panle_menu_size"))*52){
            $('#panel_auto_height').css('min-height',$(window).height()-52-82-($("#panel_ul").attr("panle_menu_size"))*52);
            $('#panel_auto_height').show();
        }
        else{
            $('#panel_auto_height').hide();
        }
        var username = localStorage['username'] + '!';
        $("#panel_username").html(username);
        $(".loadingDiv").addClass("dismiss");
        $( "#panel_menu_extend" ).panel( "open" );
        $( "#panel_menu_extend" ).removeClass();
        $(".ui-panel-dismiss").remove();

        $(".loadingDiv.dismiss").on( "tap", function( event, ui ) {
           
            panelclose();

        });
    });
    $("#panel_menu_extend").on("swipeleft",function(){ 
            panelclose();

    });
    $("#panel_menu_extend").on( "panelclose", function( event, ui ) {
        $(".loadingDiv").removeClass("dismiss");
        $( "#panel_menu_extend" ).hide();
        $( "#panel_menu_extend" ).addClass("ui-panel ui-panel-position-left ui-panel-display-overlay ui-panel-closed ui-body-inherit ui-panel-animate");

    });

    $('#news_footer').children('div').off('tap').on('tap', function(e){
        var index = $(this).index();

        if(index === 0){
            $.mobile.newChangePage("#newsroom",{ transition: "slide",reverse: false,changeHash: false});
        } else if(index === 1){
            $.mobile.newChangePage("#assistantHome",{ transition: "slide",reverse: false,changeHash: false});
        } else if(index === 2){
            $.mobile.newChangePage("#myCornerHome",{ transition: "slide",reverse: false,changeHash: false});
        } else {
            console.error('菜单不存在');
        }
    })
});